package com.notepad.ui;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.PopupWindow;
import android.widget.TimePicker;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.notepad.R;
import com.notepad.adapter.HomeListAdapter;
import com.notepad.adapter.MenuListAdapter;
import com.notepad.common.ProtocolElement;
import com.notepad.common.RequestData;
import com.notepad.common.ResponseData;
import com.notepad.domain.DrawerMenuEntity;
import com.notepad.domain.Notepad;
import com.notepad.domain.UserSetting;
import com.notepad.service.LockService;
import com.notepad.util.Constant;
import com.notepad.util.DataUtil;
import com.notepad.util.DoubleClickExitHelper;
import com.notepad.util.FileUtil;
import com.notepad.util.RefreshLayout;

public class MainActivity extends Activity {
	private ActionBar mActionBar;
	private DrawerLayout mDrawerLayout;
	private ListView mMenuListView;
    public ListView mHomeListView;
	public HomeListAdapter mHomeListAdapter;
    private DataUtil mDataUtil;
	public final int DIALOG_ID = 0;
	private RefreshLayout mRefreshLayout;
	private SwipeRefreshLayout mSwipeRefreshLayout;
	public String alarmTitle;
	private DoubleClickExitHelper mDoubleClickExitHelper;
    private static final String TAG = "responseData";
    private static final String URL = "http://tibby.aliapp.com/note";
    private RequestQueue mRequestQueue;
    private ArrayList<Notepad> mHomeList;
    private EmptyViewTipActivity mEmptyViewTipActivity;
    private FileUtil mFileUtil;
    private UserSetting mUserSetting;

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                case 2:
                    initData();
                    break;
                default:
                    break;
            }
            return false;
        }
    });


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
        initView();

        boolean flag = mFileUtil.mSaveUserSettingFile.exists();
        boolean isLock =  mFileUtil.getUserSetting().getIsLock();
        if(flag && isLock){
            // startService(new Intent(this, LockService.class));
            startActivity(new Intent(this,LockActivity.class));
        }

        setActionBar();
        initData();
        registerForContextMenu(mHomeListView);
        setListener();




	}


    private void setActionBar(){
        mActionBar = getActionBar();
        ColorDrawable drawable = new ColorDrawable(getResources().getColor(
                R.color.pink_normal));
        mActionBar.setBackgroundDrawable(drawable);
        mActionBar.setDisplayShowHomeEnabled(true);
        mActionBar.setHomeButtonEnabled(true);
        mActionBar.setDisplayUseLogoEnabled(true);
        mActionBar.setLogo(R.drawable.ic_drawer_am);
    }

    @Override
    protected void onResume() {
        super.onResume();

        initData();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    public void initView() {
        mHomeListView = (ListView) findViewById(R.id.main_content_listview);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mMenuListView = (ListView) findViewById(R.id.left_drawer);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.main_content);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.purple_normal,R.color.pink_pressed,R.color.yellow_normal,R.color.red_pressed);
		mMenuListView.setAdapter(new MenuListAdapter(this, getMenuItem()));
        mRequestQueue = Volley.newRequestQueue(this);

        mFileUtil = new FileUtil(MainActivity.this);
        mDataUtil = new DataUtil(MainActivity.this,handler);
        mDoubleClickExitHelper = new DoubleClickExitHelper(MainActivity.this);
        mEmptyViewTipActivity = new EmptyViewTipActivity();
	}
    private void setListener(){
        mMenuListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                mDrawerLayout.closeDrawers();
                switch (position) {
                    case 0:
                        mHomeListAdapter.notifyDataSetChanged();
                        break;
                    case 1:
                        Intent intent = new Intent(MainActivity.this,
                                CalendarActivity.class);
                        startActivity(intent);
                        break;
                    case 2:
                        Intent i = new Intent(MainActivity.this,SettingActivity.class);
                        startActivity(i);
                        break;
                    case 3:
                        intent = new Intent(MainActivity.this, AboutActivity.class);
                        startActivity(intent);
                        break;
                    case 4:
                        finish();
                        break;

                }

            }
        });
        mHomeListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                ArrayList<Notepad> list = mHomeListAdapter.getData();
                if (list != null && list.size() != 0) {
            Intent intent = new Intent();
            intent.setClass(MainActivity.this,
                    WriteNewNoteActivity.class);
            intent.putExtra(Constant.Note_Pad_Flag, list.get(position));
            intent.putExtra("tag", "list");
            startActivityForResult(intent, 1);
        }
    }
});
        mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh() {

                mSwipeRefreshLayout.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        initData();
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                }, 3000);
                Toast.makeText(MainActivity.this, "正在刷新...", Toast.LENGTH_SHORT).show();
            }
        });
        //上拉刷新
		/*mRefreshLayout.setOnLoadListener(new RefreshLayout.OnLoadListener() {

			@Override
			public void onLoad() {
				Toast.makeText(MainActivity.this, "load", Toast.LENGTH_SHORT).show();

				mRefreshLayout.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if(mDataUtil == null){
                            mDataUtil = new DataUtil(MainActivity.this);
                        }
                        Notepad note = new Notepad(System.currentTimeMillis(),"title","content","time");
                        mDataUtil.insertNote(note);
                        mHomeListAdapter.notifyDataSetChanged();
                        mRefreshLayout.setLoading(false);
                    }
                }, 10000);
			}
		});*/

    }
    public void initData(){
        // 从网络获取，如果网络取不到数据，加载本地缓存的数据
        RequestData requestData = new RequestData();
        requestData.setCommand(3);
        Map<String,String> map = new HashMap<>();
        map.put(ProtocolElement.REQUEST_DATA, JSON.toJSONString(requestData));
        StringRequest findRequest = new StringRequest(URL,map,new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, response.replace("\\", ""));
                ResponseData responseData = JSON.parseObject(response,ResponseData.class);
                String result = responseData.getExtra().get(ProtocolElement.NOTEPAD_LIST).toString();
                mHomeList = (ArrayList<Notepad>) JSON.parseArray(result,Notepad.class);
                if((null != mHomeList) && (mHomeList.size()>0)){

                    if (mHomeListAdapter == null) {
                        mHomeListAdapter = new HomeListAdapter(MainActivity.this, mHomeList);
                        mHomeListView.setAdapter(mHomeListAdapter);
				        mHomeListAdapter.notifyDataSetChanged();
			        } else {
				        mHomeListAdapter.setData(mHomeList);
                        mHomeListAdapter.notifyDataSetChanged();
			        }

                }else{
                    Intent intent = new Intent(MainActivity.this,EmptyViewTipActivity.class);
                    startActivity(intent);
                }
            }
        },new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG,error.getMessage());
            }
        });
        mRequestQueue.add(findRequest);

    }

	// 添加actionBar中的item--添加新记事
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater mMenuInflater = getMenuInflater();
		mMenuInflater.inflate(R.menu.action_menu, menu);
		return true;
	}

	// anctionBar中New按钮的点击事件。
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_add_item:
			createNewNote();
			break;

		case android.R.id.home:
			if (mDrawerLayout.isDrawerVisible(GravityCompat.START)) {
				mDrawerLayout.closeDrawer(GravityCompat.START);
			} else {
				mDrawerLayout.openDrawer(GravityCompat.START);
			}
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	public void createNewNote() {
		Intent intent = new Intent();
		intent.setClass(MainActivity.this, WriteNewNoteActivity.class);
		intent.putExtra("tag", "home");
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivityForResult(intent, 1);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == 10) {
//			if (mHomeListAdapter == null) {
//				mHomeListAdapter = new HomeListAdapter(this, getHomeList());
//				mHomeListView.setAdapter(mHomeListAdapter);
//				mHomeListAdapter.notifyDataSetChanged();
//			} else {
//				mHomeListAdapter.setData(getHomeList());
//			}
            initData();
		}
	}

	// LeftMenu获取数据
	private ArrayList<DrawerMenuEntity> getMenuItem() {
		ArrayList<DrawerMenuEntity> list = new ArrayList<DrawerMenuEntity>();
		DrawerMenuEntity data = null;
		data = new DrawerMenuEntity(R.drawable.menu_icon_home, "首页");
		list.add(data);
		data = new DrawerMenuEntity(R.drawable.menu_icon_calendar, "日历");
		list.add(data);
        data = new DrawerMenuEntity(R.drawable.menu_icon_setting, "设置");
        list.add(data);
		data = new DrawerMenuEntity(R.drawable.menu_icon_about, "关于");
		list.add(data);
		data = new DrawerMenuEntity(R.drawable.menu_icon_qiut, "退出");
		list.add(data);
		return list;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		menu.setHeaderIcon(R.drawable.ic_launcher);
		menu.setHeaderTitle(R.string.menu);
		getMenuInflater().inflate(R.menu.context_menu, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		final ArrayList<Notepad> list = mHomeListAdapter.getData();
		switch (item.getItemId()) {
		case R.id.menu_item_delete:
			new AlertDialog.Builder(this)
					.setTitle(R.string.delete)
					.setMessage(R.string.delete_dialog_message)
					.setIcon(android.R.drawable.ic_delete)
					.setPositiveButton(R.string.yes, new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Notepad note = list.get(info.position);
                            mDataUtil.deleteNote(note);
                            mHomeListAdapter.getData().remove(note);
                            mHomeListAdapter.notifyDataSetChanged();
                            dialog.dismiss();
                        }
                    })
					.setNegativeButton(R.string.cancle, new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();

			break;
		case R.id.menu_item_edit:
			if (list != null && list.size() != 0) {
				Intent intent = new Intent(this, WriteNewNoteActivity.class);
				intent.putExtra(Constant.Note_Pad_Flag, list.get(info.position));
				intent.putExtra("tag", "list");
				startActivityForResult(intent, 1);
			}
			break;
		case R.id.menu_item_alarm:
			showDialog(DIALOG_ID);
			alarmTitle ="您的 "+ list.get(info.position).getTitle()+" 时间到了！";
			break;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {
		case DIALOG_ID:
			Calendar current_time = Calendar.getInstance();
			final AlarmManager alarmManager = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
			dialog = new TimePickerDialog(MainActivity.this, 0,
					new OnTimeSetListener() {

						@Override
						public void onTimeSet(TimePicker view, int hourOfDay,
								int minute) {
							Intent intent = new Intent();
							intent.putExtra("alarm_msg", alarmTitle);
							sendBroadcast(intent);
							intent.setAction(Constant.ALARM_ACTION);
							PendingIntent pi = PendingIntent.getBroadcast(
									MainActivity.this, 0, intent, 0);
							Calendar c = Calendar.getInstance();
							c.set(Calendar.HOUR_OF_DAY, hourOfDay);
							c.set(Calendar.MINUTE, minute);
							alarmManager.set(AlarmManager.RTC_WAKEUP,
									c.getTimeInMillis(), pi);
							Toast.makeText(MainActivity.this, "您的提醒已经设置成功",
									Toast.LENGTH_SHORT).show();
						}
					}, current_time.get(Calendar.HOUR_OF_DAY),
					current_time.get(Calendar.MINUTE), true);
			break;

		}

		return dialog;
	}

    /**
     * 双击退出和按menu键弹出侧滑菜单
     */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			if(mDrawerLayout.isDrawerOpen(Gravity.START)){
				mDrawerLayout.closeDrawers();
				return true;
			}
			return mDoubleClickExitHelper.onKeyDown(keyCode, event);
		}
		if(keyCode == KeyEvent.KEYCODE_MENU){
			if(mDrawerLayout.isDrawerOpen(Gravity.START)){
				mDrawerLayout.closeDrawers();
				return true;
			}else{
				mDrawerLayout.openDrawer(Gravity.START);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

}
